package com.chukun.disruptor.basic;

import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import java.nio.ByteBuffer;
import java.util.concurrent.*;

/**
 * 主程序
 */
public class MainRunner {

    public static void main(String[] args) {

        OrderEventFactory eventFactory = new OrderEventFactory();

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        int ringBufferSize = 1024*1024;

        /**
         * 构建disruptor的实例
         * 1.指定消费者的工厂
         * 2.指定ringBufferSize 的大小
         * 3.指定线程池
         * 4.指定ProducerType 生产者模型
         * 5.指定等待策略
         */
        Disruptor disruptor = new Disruptor<OrderEvent>(eventFactory,ringBufferSize,executorService, ProducerType.SINGLE,new BlockingWaitStrategy());

        //将disruptor与消费者的处理类管理起来
        disruptor.handleEventsWith(new OrderEventHandler());

        //启动disruptor
        disruptor.start();

        //获取ringBuffer
        RingBuffer ringBuffer = disruptor.getRingBuffer();

        //构建生产者对象
        OrderEventProducer orderEventProducer = new OrderEventProducer(ringBuffer);

        ByteBuffer buffer = ByteBuffer.allocate(8);

        for(long i=0;i<100;i++){
            buffer.putLong(0,i);
            orderEventProducer.sendData(buffer);
        }

        //关闭disruptor
        disruptor.shutdown();

        //关闭线程池
        executorService.shutdown();

    }
}
